import allure
from playwright.sync_api import Page

class DialogKeywords:
    def __init__(self, page: Page):
        self.page = page

    def accept_dialog(self, text: str = None, time_out=12):
        """
        确认弹窗
        :param text: 预期弹窗文本(可选)
        """
        step_desc = "确认弹窗" if text is None else f"确认弹窗: {text}"
        with allure.step(step_desc):
            try:
                self.page.on('dialog', lambda dialog: dialog.accept())
                if text:
                    self.page.wait_for_event('dialog', lambda dialog: dialog.message == text, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise

    def dismiss_dialog(self, text: str = None, time_out=12):
        """
        取消弹窗
        :param text: 预期弹窗文本(可选)
        """
        step_desc = "取消弹窗" if text is None else f"取消弹窗: {text}"
        with allure.step(step_desc):
            try:
                self.page.on('dialog', lambda dialog: dialog.dismiss())
                if text:
                    self.page.wait_for_event('dialog', lambda dialog: dialog.message == text, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise

    def input_dialog(self, prompt_text: str, input_text: str, time_out=12):
        """
        弹窗输入
        :param prompt_text: 预期弹窗文本
        :param input_text: 要输入的文本
        """
        step_desc = f"在弹窗输入: {input_text}"
        with allure.step(step_desc):
            try:
                self.page.on('dialog', lambda dialog: dialog.accept(prompt_text=input_text))
                self.page.wait_for_event('dialog', lambda dialog: dialog.message == prompt_text, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise